class ReaderController < ApplicationController
  
  before_filter :verify_session
  
  def index
    list
  end
  
  def list
    @readers_pages, @readers = paginate :readers, :per_page => 10, :conditions =>'is_admin = false'  
     render :action => 'list'
  end
  
  def new
    init
    @reader = Reader.new
    @reader.is_admin=false
#    @reader.picture="default_head.gif"
    
    @picture_lob = PictureLob.new
    
  end
  
  def create
    @reader = Reader.new(params[:reader])
    
#    此处的逻辑为,先将图片存入表picture_lob.之后,再将生成的url填入reader的picture字段
#    if params[:picture_lob][:picture].original_filename!=""
#       @picture_lob = PictureLob.new(params[:picture_lob])
#       @picture_lob.description = @reader.reader_name+"的头像"
#       @picture_lob.save
#       @picture_lob.id 
#       @reader.picture = @picture_lob.id
#    end
    
    if @reader.save 
      flash[:notice] = "创建成功"
      redirect_to :action => 'list'
    else
      flash[:notice] = "创建失败"  
      render :action => 'new'
    end
  end
  
  def edit
    init
    @reader = findById(params[:id])
    if @reader.picture && !@reader.picture.empty?
      @picture_lob = PictureLob.find(@reader.picture)
    end
  end
  
  def update
    @reader = findById(params[:id])
    
#    if params[:picture_lob][:picture].original_filename!="" 
#       if @reader.picture && !@reader.picture.empty?
##      用户更新前有头像,并且此次更新头像
#          @picture_lob = PictureLob.find(@reader.picture)
#       else
##      用户更新前没有头像
#          @picture_lob = PictureLob.new
#       end
#       @picture_lob.lob = params[:picture_lob][:picture].read
#       @picture_lob.description = params[:reader][:reader_name]+"的头像"
#       @picture_lob.save
#       @reader.picture = @picture_lob.id
#    end
    
    if @reader.update_attributes(params[:reader])
      flash[:notice] = "更新成功"
    else
      flash[:notice] = "更新失败"
    end
      render :action => 'show'
  end
  
  def destroy
    reader = findById(params[:id])
    if reader.picture
      picture_lob = PictureLob.find(reader.picture).destroy
    end
    reader.destroy
    redirect_to :action=>'list'
  end
 
  def show 
    @reader = findById(params[:id])
    render :layout => false
  end
 
  private 
  def findById(id)
    Reader.find(id)
  end
  
  def init
    @departments = Department.find(:all)
  end
  
end
